package com.totem.base.util;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Random;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
@Slf4j
public class NetworkUtil {

    public static int randomPort(int start, int end) throws IOException {
        Random random = new Random();
        int randomNum = end-start+1;
        int port = random.nextInt(randomNum)+start;
        int count = 0;
        while(count<randomNum && portIsUsed(port)) {
            count++;
            port = random.nextInt(randomNum)+start;
        }
        if(count>=randomNum){
            throw new IOException(String.format(
                    "Port[%d-%d] was already in use", start, end));
        }
        return port;
    }

    public static boolean portIsUsed(int port){
        boolean used = false;
        Socket socket = null;
        try {
            socket = new Socket();
            socket.bind(new InetSocketAddress(port));
        } catch (IOException e) {
            used = true;
        } finally {
            try {
                if(used && socket!=null) {
                    socket.close();
                }
            } catch (IOException e) {
            }
        }
        return used;
    }
}
